package com.example.springbootdemo.es7;

import org.apache.http.HttpHost;
import org.elasticsearch.client.RestClient;
import org.elasticsearch.client.RestClientBuilder;
import org.elasticsearch.client.RestHighLevelClient;

public class ConnectElasticsearch {
    public static void connect(ElasticsearchTask... tasks) {
        // 创建低级 REST 客户端
        HttpHost httpHost = new HttpHost("localhost", 9200, "http");
        RestClientBuilder builder = RestClient.builder(httpHost);
        // 创建高级客户端
        RestHighLevelClient client = new RestHighLevelClient(builder);
        try {
            // 执行任务
            for (ElasticsearchTask task : tasks) {
                task.doSomething(client);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                client.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}
